package com.example.shopping.controller;

import com.example.shopping.config.Validator;
import com.example.shopping.entity.User;
import com.example.shopping.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@RequestMapping("/user")//公共路径
public class UserController {
    @Autowired
    private UserService userService;

    //进入登陆页面
    @GetMapping("/login")
    public String login(HttpSession session) {
        //判断用户是否已经登陆，登陆则重定向到主页
        if (session.getAttribute("user") != null) {
            return "redirect:/";
        }

        return "login";
    }

    //安全退出
    @GetMapping("/logout") // /user/logout
    public String loginout(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user != null) {
            session.removeAttribute("loginUser");//删除登录数据
            userService.logout(user.getId());
        }

        return "redirect:/user/login";
    }

    //进行登录请求
    @PostMapping("/login")
    public String login(@RequestParam String account, @RequestParam String password, HttpSession session, Model model) {
        User user = userService.login(account, password);
        if (user == null) {
            model.addAttribute("msg", "账户或密码错误");
            //重定向到某个页面
            return "login";
        } else {
            //将登录用户保存到会话
            session.setAttribute("loginUser", user);
            //进入首页
            return "redirect:/";
        }
    }

    //导向到注册页面
    @GetMapping("/register")
    public String register() {
        return "register";
    }

    //注册功能
    @PostMapping("/register")
    @ResponseBody
    public String register(@RequestParam String account,
                           @RequestParam String password,
                           @RequestParam String telphone,
                           @RequestParam String email,
                           @RequestParam String avatar
    ) throws Exception {
        //验证用户名和密码是否符合要求
        if (!Validator.validateAccount(account)) {
            return "fail:用户名不符合要求";
        }
        if (!Validator.validatePassword(password)) {
            return "fail:密码不符合要求";
        }
        if (!Validator.validatePhone(telphone)) {
            return "fail:手机号码不符合要求";
        }

        boolean re = userService.insertUser(account, password, telphone, email, avatar);
        if (re) {
            return "success";
        }
        return "fail";
        //return "redirect:/user/register";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestPart MultipartFile file) throws Exception {
        String url = userService.saveAvatar(file);
        return url;
    }
}
